package com.shr.lease.web.admin.custom.shedule;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.shr.lease.model.entity.BrowsingHistory;
import com.shr.lease.model.entity.LeaseAgreement;
import com.shr.lease.model.entity.ViewAppointment;
import com.shr.lease.model.enums.AppointmentStatus;
import com.shr.lease.model.enums.LeaseStatus;
import com.shr.lease.web.admin.controller.lease.LeaseAgreementController;
import com.shr.lease.web.admin.service.BrowsingHistoryService;
import com.shr.lease.web.admin.service.LeaseAgreementService;
import com.shr.lease.web.admin.service.ViewAppointmentService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Haoran Sun
 * @since 2024/06/21
 */

@Component
public class ScheduledTasks {

    @Resource
    private LeaseAgreementService leaseAgreementService;
    @Resource
    private ViewAppointmentService viewAppointmentService;
    @Resource
    private BrowsingHistoryService browsingHistoryService;


    /**
     * 每日0点0时0分检查租约信息的状态
     *
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void checkLeaseAgreement() {
        leaseAgreementService.update(
                new LambdaUpdateWrapper<LeaseAgreement>()
                        .le(LeaseAgreement::getLeaseEndDate,new Date())
                        .in(LeaseAgreement::getStatus, LeaseStatus.SIGNED,LeaseStatus.WITHDRAWING)
                        .set(LeaseAgreement::getStatus, LeaseStatus.EXPIRED)
        );
    }

    /**
     * 每日0点0时0分检查预约信息的状态
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void checkViewAppointment(){
        viewAppointmentService.update(
                new LambdaUpdateWrapper<ViewAppointment>()
                        .le(ViewAppointment::getAppointmentTime,new Date())
                        .in(ViewAppointment::getAppointmentStatus, AppointmentStatus.WAITING)
                        .set(ViewAppointment::getAppointmentStatus, AppointmentStatus.EXPIRED)
        );
    }

    /**
     * 每日0点0时0分删除大于30天的公寓浏览记录
     * 若用户记录数大于200条则对超出的条数进行删除
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void delteBrowsingHistory(){
        //删除大于30天的公寓浏览记录
        browsingHistoryService.remove(
                new LambdaQueryWrapper<BrowsingHistory>()
                        .le(BrowsingHistory::getBrowseTime, Date.from(LocalDate.now()
                                                .minusDays(30)
                                                .atStartOfDay(ZoneId.systemDefault())
                                                .toInstant())));
        //若用户记录数大于200条则对超出的条数进行删除
        //1、查询所有用户id
        List<Long> userIds = browsingHistoryService.selectAllUserId();
        //2、查询浏览历史记录数大于200的用户  执行删除超出条数的操作

        for (Long userId : userIds) {
            long count = browsingHistoryService.count(new LambdaQueryWrapper<BrowsingHistory>().eq(BrowsingHistory::getUserId, userId));
            if (count > 200) {
                browsingHistoryService.removeOldRecords(count - 200,userId);
            }
        }
        userIds.stream().collect(Collectors.toMap(
                Function.identity(),
                userId -> browsingHistoryService.count(new LambdaQueryWrapper<BrowsingHistory>().eq(BrowsingHistory::getUserId, userId))
        ))
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue() > 200)
                .forEach(entry -> browsingHistoryService.removeOldRecords(200,entry.getKey()));


    }



}
